import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import {connect, history} from 'umi'
import { stringify } from 'qs'
import { Page } from 'components'
import {Modal,Button, Row, Space, notification, message} from "antd";
import SqlModal from "./components/SqlModal";
import JSZip from 'jszip'
import saveAs from 'file-saver'
import BasePathTreeModal from "../components/BasePathTreeModal";
import ShowCodeModal from '../components/ShowCodeModal'
import TableDetails from '../../code_table_column/index'
import {DownloadOutlined, UploadOutlined} from '@ant-design/icons'

@connect(({ code_table_detail, loading }) => ({ code_table_detail, loading }))
class CodeTable extends PureComponent {
  handleRefresh = newQuery => {
    const { location } = this.props
    const { query, pathname } = location
    if(newQuery && newQuery.createTime) {
      newQuery.startDate = newQuery.createTime[0]
      newQuery.endDate = newQuery.createTime[1]
      delete newQuery.createTime
    }
    history.push({
      pathname,
      search: stringify(
        {
          ...query,
          ...newQuery,
        },
        { arrayFormat: 'repeat' }
      ),
    })
  }


  get showSqlProps() {
    const { location, dispatch, code_table_detail} = this.props

    return {
      showSql: code_table_detail.showSql,
      onCancel() {
        dispatch({
          type: "code_table_detail/hideSqlModal"
        })
      },
      onExec(data) {
        //执行创建语句
        dispatch({
          type: 'code_table_detail/queryExec',
          payload: {id: code_table_detail.showSql.tableId, ...data},
        }).then((res)=>{
          // const [messageApi] = message.useMessage();
          message.info(res.res, 30);
        })
      },
    }
  }

  get showCodeProps() {
    const {location, dispatch, code_table_detail, options} = this.props

    return {
      code_table: code_table_detail,
      queryCodeFile(payload) {
        dispatch({
          type: "code_table_detail/queryCodeFile",
          payload: payload
        })
      },
      queryTemplate(payload) {
        dispatch({
          type: "code_table_detail/queryCodeTableTemplateByGroupId",
          payload: payload
        }).then((templateMap)=>{
          let keys = Object.keys(templateMap)
          if(keys.length>0) {
            //请求同步默认代码信息
            dispatch({
              type: "code_table_detail/queryCodeFile",
              payload: {
                id: code_table_detail.currentItem.id,
                templateId: keys[0],
                path: code_table_detail.selectBasePath,
                codeNamespace: code_table_detail.codeNamespace
              }
            })

          }
        })

        //请求分组目录信息
        dispatch({
          type: "code_table_detail/queryBaseDirTree",
          payload: {groupId: payload.groupId}
        })
      },
      onSaveCode(payload) {
        dispatch({
          type: "code_table_detail/querySaveCode",
          payload: payload
        }).then(function (res) {
          if(res.code === 5000) {
            notification.error({message: "保存失败， 请检查脚本"})
          } else {
            notification.success({message: "保存成功"})
          }
        })
      },
      //获取代码
      getCodes(payload) {
        dispatch({
          type: "code_table_detail/queryCodes",
          payload: payload
        }).then(function (res) {
          if(res.code === 5000) {
            notification.error({message: "创建失败， 请检查脚本"})
          } else {
            notification.success({message: "代码包创建成功"})
            //打包下载
            var zip = new JSZip();
            for(var file in res.payload) {
              zip.file(file, res.payload[file])
            }
            zip.generateAsync({type: "blob"})
              .then(function (content) {
                saveAs(content, "code.zip")
              })
          }
        })
      },
      //变更命名空间
      onChangeCodeNamespace(namespace) {
        dispatch({
          type: "code_table_detail/updateState",
          payload: {codeNamespace: namespace}
        })
      },
      //显示目录选择框
      showSelectDir() {
        dispatch({
          type: "code_table_detail/updateState",
          payload: {showBasePath: true}
        })
      },
      options: code_table_detail.options,
      showCode: code_table_detail.showCode,
      onCancel() {
        dispatch({
          type: "code_table_detail/hideCode",
        })
      }
    }
  }

  //目录选择框属性
  get showSelectDirProps() {
    const {location, dispatch, code_table_detail, options} = this.props
    return ({
      onCancel: () => {
        dispatch({
          type: "code_table_detail/updateState",
          payload: {showBasePath: false}
        })
      },
      onOk: (res) => {
        dispatch({
          type: "code_table_detail/updateState",
          payload: {showBasePath: false, selectBasePath: res}
        })
      }
    })
  }

  render() {
    const {code_table_detail, location, dispatch,} = this.props;

    return (
      <Page inner>

        <Row>
          <Space>
            <Button  type="primary" onClick={()=>{
              dispatch({
                type: 'code_table_detail/queryDiffSql',
                payload: {
                  id: code_table_detail.currentItem.id,
                },
              })
            }}
            icon={<UploadOutlined />}
            >系统同步到数据库</Button>
            <Button icon={<DownloadOutlined />}
                    type={"primary"}
                    onClick={()=>{
                      dispatch({
                        type: 'code_table_detail/updateSyncTable2CodeTable',
                        payload: {
                          id: code_table_detail.currentItem.id,
                        },
                      }).then(data=>{
                        if(data.code === 2000) {
                          notification.success({message: "同步成功"})
                        } else {
                          notification.error({message: "同步失败"})
                        }
                      })
                    }}
                    >数据库同步到系统</Button>
            <Button  type="primary" onClick={()=>{
              dispatch({
                type: 'code_table_detail/querySql',
                payload: {
                  id: code_table_detail.currentItem.id,
                },
              })
            }}>查看创建SQL</Button>
            {/*<Button  type="primary">同步到DB</Button>*/}
            <Button  type="primary" onClick={()=>{
              dispatch({
                type: 'code_table_detail/showCode',
                payload: {
                  id: code_table_detail.currentItem.id,
                },
              })
            }}>生成代码</Button>
          </Space>

        </Row>


        <TableDetails location={location} dispatch={dispatch} />

        <SqlModal {...this.showSqlProps} />
        <ShowCodeModal {...this.showCodeProps} />
        <BasePathTreeModal code_table={code_table_detail} showBasePath={code_table_detail.showBasePath} {...this.showSelectDirProps} />
      </Page>
    )
  }
}

CodeTable.propTypes = {
  code_table_detail: PropTypes.object,
  loading: PropTypes.object,
  location: PropTypes.object,
  dispatch: PropTypes.func,
}

export default CodeTable

